//
//  SearchDetailViewController.m
//  GentlemanAnime
//
//  Created by dllo on 15/7/6.
//  Copyright (c) 2015年 lanou3g.com 蓝欧科技. All rights reserved.
//

#import "SearchDetailViewController.h"
#import "AFNetworking.h"
#import "AFNetworkReachabilityManager.h"
#import "UIImageView+WebCache.h"
#import "SearchDetailModel.h"
#import "SearchDetailViewCell.h"
#import "AnimeDetallsViewController.h"
#import "MBProgressHUD.h"


@interface SearchDetailViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,retain)UITableView *SearchDetailView;
@property(nonatomic,retain)NSMutableArray *SearchDetailArr;
@property(nonatomic,retain)UISearchBar *SearchDetailBar;
@property(nonatomic,retain)MBProgressHUD *SearchDetailHUD;

@end

@implementation SearchDetailViewController
- (void)dealloc
{
    [_SearchDetailHUD release];
    [_SearchDetailView release];
    [_SearchDetailArr release];
    [_SearchDetailBar release];
    [_SearchDetailName release];

    [super dealloc];
}

//初始化方法
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.SearchDetailArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //搜索详情页面
    self.navigationController.navigationBar.translucent = NO;

    //做一个搜索详情的searchBar
    self.SearchDetailBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 10, 30)];
    self.SearchDetailBar.layer.borderColor = [UIColor whiteColor].CGColor;
    self.navigationItem.titleView = self.SearchDetailBar;
    //搜索栏的占位符
    self.SearchDetailBar.placeholder = @"漫画名、作者";
    self.SearchDetailBar.clearsContextBeforeDrawing = YES;
    //后添加的代理人
    self.SearchDetailBar.delegate = self;

    self.SearchDetailView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];

    [self.view addSubview:self.SearchDetailView];
    self.SearchDetailView.dataSource = self;
    self.SearchDetailView.delegate = self;
    self.SearchDetailView.rowHeight = ([UIScreen mainScreen].bounds.size.height - 64) / 4;
    [_SearchDetailView release];
    
    //小菊花
    self.SearchDetailHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.SearchDetailHUD.mode = MBProgressHUDModeIndeterminate;
    self.SearchDetailHUD.color = [UIColor colorWithRed:0.334 green:0.619 blue:1.000 alpha:1.000];

    [self createData];
  
}
//解析详情页面
-(void)createData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [self.SearchDetailName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *strURL = [NSString stringWithFormat:@"http://api.dmzj.com/dynamic/comicsearch/%@.json",str];
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *arr = dic[@"data"];
        if (arr.count == 0 ) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"搜索内容无法找到" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        } else {
            for (NSDictionary *tempDic in arr) {
                SearchDetailModel *searchDModel = [[SearchDetailModel alloc]init];
                [searchDModel setValuesForKeysWithDictionary:tempDic];
                [self.SearchDetailArr addObject:searchDModel];
                [searchDModel release];
            }
        }
        [self.SearchDetailView reloadData];
        [self.SearchDetailHUD hide:YES];
        [self.SearchDetailHUD removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.SearchDetailArr.count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *reuse = @"reuse";
    SearchDetailViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[SearchDetailViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse]autorelease];
    }
    SearchDetailModel *searchDModel = self.SearchDetailArr[indexPath.row];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:searchDModel.cover]];
    cell.titleLabel.text = searchDModel.title;
    cell.authorLabel.text = searchDModel.authors;
    cell.zoneLabel.text = searchDModel.types;
    cell.nameLabel.text = searchDModel.last_update_chapter_name;

       return cell;
}


#pragma maek tableView的点击方法
////点击调转到动漫页面()
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnimeDetallsViewController *AnimeDetailsVC = [[AnimeDetallsViewController alloc]init];
    [self.navigationController pushViewController:AnimeDetailsVC animated:YES];
    SearchDetailModel *searchDetailModel = self.SearchDetailArr[indexPath.row];
    AnimeDetailsVC.Id = searchDetailModel.SearchId;
    AnimeDetailsVC.title = searchDetailModel.title;
}



//搜索栏的点击事件
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.SearchDetailBar resignFirstResponder];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.SearchDetailView animated:YES ];
    //小菊花的类型
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.color = [UIColor colorWithRed:0.334 green:0.619 blue:1.000 alpha:1.000];
    
    [self.SearchDetailBar setKeyboardType:UIKeyboardTypeEmailAddress];
    //设置return键的样式
    self.SearchDetailBar.returnKeyType = UIReturnKeyDone;
    
    self.SearchDetailName = self.SearchDetailBar.text;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [self.SearchDetailName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *strURL = [NSString stringWithFormat:@"http://api.dmzj.com/dynamic/comicsearch/%@.json",str];
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.SearchDetailArr removeAllObjects];
        NSDictionary *dic = responseObject;
        NSArray *arr = dic[@"data"];
        if (arr.count == 0 ) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"搜索内容无法找到" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        } else {
            for (NSDictionary *tempDic in arr) {
            SearchDetailModel *searchDModel = [[SearchDetailModel alloc]init];
            [searchDModel setValuesForKeysWithDictionary:tempDic];
            [self.SearchDetailArr addObject:searchDModel];
            [searchDModel release];
            }
        }
        [self.SearchDetailView reloadData];
        [hud hide:YES];
        [hud removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
